package com.exchange.service.impl;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.exchange.entity.pojo.*;
import com.exchange.entity.vo.MyWalletVo;
import com.exchange.entity.vo.PackageVo;
import com.exchange.entity.vo.PackagecVo;
import com.exchange.mapper.*;
import com.exchange.service.WalletService;
import com.exchange.until.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;

/**
* @author Administrator
* @description 针对表【wallet】的数据库操作Service实现
* @createDate 2024-04-25 20:02:10
*/
@Slf4j
@Service
public class WalletServiceImpl extends ServiceImpl<WalletMapper, Wallet>
    implements WalletService{

        @Autowired
        private WalletMapper walletMapper;

        @Autowired
        private RedisTemplate<String,String> redisTemplate;

        @Autowired
        private PackageTimeMapper packageTimeMapper;

        @Autowired
        private VoltageMapper voltageMapper;

        @Autowired
        private PowerTypeMapper powerTypeMapper;

        @Autowired
        private PackageRecordMapper packageRecordMapper;

        @Autowired
        private CardRollMapper cardRollMapper;

        @Autowired
        private CardDisplayMapper cardDisplayMapper;

        @Autowired
        private UserDetailMapper userDetailMapper;


        @Override
        public Result<String> buyPackage(String token) {
            if (StrUtil.isBlank(token)){
                throw new RuntimeException("token不能为空");
            }
            String token1 = this.redisTemplate.opsForValue().get("user:login"+token);
            User user = JSON.parseObject(token1, User.class);
            Long id = user.getId();

            //钱包不会因为你没有缴纳押金而不存在，我们的钱包本身就存在
            Wallet wallet = this.walletMapper.buyPackage(id);
            if (new BigDecimal(0.00).compareTo(wallet.getMoney())==0 || wallet.getMoney()==null){
                return Result.error("押金不足");
            }
            return new Result<>(200,"押金已缴纳",true,null);
        }

        @Override
        public void ya(Wallet wallet,String token) {
            if (StrUtil.isBlank(token)){
                throw new RuntimeException("token不能为空");
            }
            String token1 = this.redisTemplate.opsForValue().get("user:login"+token);
            User user = JSON.parseObject(token1, User.class);
            Long id = user.getId();
            BigDecimal walletMoney = wallet.getMoney();
            this.walletMapper.inserts(id,walletMoney);
        }

        @Override
        public void tui( String token) {
            if (StrUtil.isBlank(token)){
                throw new RuntimeException("token不能为空");
            }
            String token1 = this.redisTemplate.opsForValue().get("user:login"+token);
            User user = JSON.parseObject(token1, User.class);
            Long id = user.getId();
            this.walletMapper.updates(id);
        }

        @Override
        public BigDecimal jia(PackageRecord packageRecord) {
            //电池
            Long ptid = packageRecord.getPtid();
            //电压
            Long vid = packageRecord.getVid();
            //时间
            Long patid = packageRecord.getPatid();
            //拿到用户自己的卡卷
            Long id = packageRecord.getId();
            CardDisplay cardDisplay = this.cardDisplayMapper.selectLists(id);
            System.err.println("cardDisplay------>"+cardDisplay);

            PackageTime packageTime = this.packageTimeMapper.selectById(patid);
            Voltage voltage = this.voltageMapper.selectById(vid);
            PowerType powerType = this.powerTypeMapper.selectById(ptid);
            BigDecimal timePrice = packageTime.getPrice();
            BigDecimal voltagePrice = voltage.getPrice();
            BigDecimal powerTypePrice = powerType.getPrice();

            if (cardDisplay!=null){
            //拿到套餐卡卷的金额
            Integer type = cardDisplay.getType();
            if (type==0){
                BigDecimal countPrice = cardDisplay.getCountPrice();
                //获取到卡卷进行减价
                BigDecimal allPrice = timePrice.add(voltagePrice).add(powerTypePrice).subtract(countPrice);
                System.out.println("卡卷进行减价：allPrice------>allPrice------>"+allPrice);
                this.cardRollMapper.updatere(id);
                return allPrice;
             }
            }

            //相加
            BigDecimal allPrice = timePrice.add(voltagePrice).add(powerTypePrice);
            log.info("卡卷的相加：allPrice------>{}",allPrice);
            return allPrice;
        }

        @Override
        public void buys(PackageRecord packageRecord,String token) {
            if (StrUtil.isBlank(token)){
                throw new RuntimeException("token不能为空");
            }
            if (ObjectUtil.isEmpty(packageRecord)){
                Result.error("套餐不能为空");
            }
            //拿到用户信息
            String token1 = this.redisTemplate.opsForValue().get("user:login"+token);
            User user = JSON.parseObject(token1, User.class);
            Long uid = user.getId();
            //拿到套餐外键
            Long ptid = packageRecord.getPtid();
            //拿到电压外键
            Long vid = packageRecord.getVid();
            //套餐时长外键
            Long patid = packageRecord.getPatid();
            //拿到套餐信息
            PackageTime packageTime = this.packageTimeMapper.selectById(patid);
            if (ObjectUtil.isEmpty(packageTime)){
                Result.error("套餐时长不能为");
            }
            //拿到电压信息
            Voltage voltage = this.voltageMapper.selectById(vid);
            if (ObjectUtil.isEmpty(voltage)){
                Result.error("电压不能为");
            }
            //拿到套餐类型信息
            PowerType powerType = this.powerTypeMapper.selectById(ptid);
            //拿到用户钱包信息
            Long wid = this.walletMapper.selectByUid(uid);
            //通过用户编号拿到电瓶表状态
            QueryWrapper<UserDetail> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("uid",uid);
            UserDetail userDetail = this.userDetailMapper.selectOne(queryWrapper);
            if (ObjectUtil.isEmpty(userDetail)){
                Result.error("用户电瓶表状态不能为");
            }
            System.err.println("userDetail------>"+userDetail);
            //拿到用户自己选择的电压类型
            Long remark = voltage.getRemark();
            System.err.println("remark------>"+remark);
            if (userDetail!=null) {
                //用户使用的卷有两种类型 ：一种是价格优惠卷   一种是时间增加卷
                //做判断  在考虑是价钱减免还是时长增加

                //拿到用户自己的卡卷
                Long id = packageRecord.getId();
                CardDisplay cardDisplay = this.cardDisplayMapper.selectLists(id);
                if (ObjectUtil.isEmpty(cardDisplay)){
                    Result.error("卡卷不能为");
                }
                System.err.println("cardDisplay------>" + cardDisplay);
                if (cardDisplay != null) {
                    //拿到套餐卡卷的天数
                    Integer type = cardDisplay.getType();
                    //套餐卷时长中的天数
                    if (type == 1) {
                        Integer count = 0;
                        //卡卷的天数
                        Integer day = cardDisplay.getDay();
                        //套餐时长中的天数
                        Integer countDays = packageTime.getCountDays();
                        //获取到卡卷天数进行购买套餐的天数进行相加
                        count += countDays + day;
                        System.err.println("卡卷的相加：count------>卡卷进行相加：count------>count------>" + count);
                        //当前时间
                        Date date = DateUtil.date();
                        //常用偏移：套餐到期时间
                        DateTime newDate2 = DateUtil.offsetDay(date, count);
                        //更新用户拥有的卡卷状态值
                        this.cardRollMapper.updatere(id);
                        //添加到用户表中电压类型
                        this.userDetailMapper.updater(uid, remark);
                        //购买套餐成功
                        this.packageRecordMapper.inserts(wid, ptid, vid, patid, newDate2);
                    } else {
                        //套餐时长中的天数
                        Integer countDays = packageTime.getCountDays();
                        //当前时间
                        Date date = DateUtil.date();
                        //常用偏移：套餐到期时间
                        DateTime newDate2 = DateUtil.offsetDay(date, countDays);
                        //更新用户拥有的卡卷状态值
                        this.cardRollMapper.updatere(id);
                        //添加到用户表中电压类型
                        this.userDetailMapper.updater(uid, remark);
                        //购买套餐成功
                        this.packageRecordMapper.inserts(wid, ptid, vid, patid, newDate2);
                    }

                } else {
                    //套餐时长中的天数
                    Integer countDays = packageTime.getCountDays();
                    //当前时间
                    Date date = DateUtil.date();
                    //常用偏移：套餐到期时间
                    DateTime newDate2 = DateUtil.offsetDay(date, countDays);
                    //更新用户拥有的卡卷状态值
                    this.cardRollMapper.updatere(id);
                    //添加到用户表中电压类型
                    this.userDetailMapper.updater(uid, remark);
                    //购买套餐成功
                    this.packageRecordMapper.inserts(wid, ptid, vid, patid, newDate2);
                }
            }else {
                //添加到用户表中电压类型
                this.userDetailMapper.insertr(remark);
            }
        }

    /**
     * 进行套餐续费时购买
     * @param packageVo
     */
    @Override
        public void xufei(PackageVo packageVo) {
            Long id = packageVo.getId();
            PackageRecord packageRecord1 = this.packageRecordMapper.selectById(id);
            Long patid = packageVo.getPatid();
            PackageTime packageTime = this.packageTimeMapper.selectById(patid);
            //套餐时长中的天数
            Integer count = packageTime.getCountDays();
            //拿到用户自己的拥有时间
            Date expirationTime = packageRecord1.getExpirationTime();
//            //常用偏移：套餐到期时间
//            DateTime newDate2 = DateUtil.offsetDay(expirationTime, count);


            //拿到用户自己的卡卷
            Long cid = packageVo.getCid();
            CardDisplay cardDisplay = this.cardDisplayMapper.selectListc(cid);
            System.err.println("cardDisplay------>"+cardDisplay);
            if (cardDisplay!=null){
                //拿到套餐卡卷的天数
                Integer type = cardDisplay.getType();
                if (type==1){
                    Integer counts = 0;
                    //卡卷的天数
                    Integer day = cardDisplay.getDay();
                    //套餐时长中的天数
                    Integer countDays = packageTime.getCountDays();
                    //获取到卡卷天数进行购买套餐的天数进行相加
                    counts += countDays + day;
                    System.err.println("卡卷的相加：count------>卡卷进行相加：count------>count------>"+counts);
                    //常用偏移：套餐到期时间
                    DateTime newDate3 = DateUtil.offsetDay(expirationTime, count);
                    //更新卡卷
                    this.cardRollMapper.updaterec(cid);

                    this.packageRecordMapper.updatess(id,newDate3);
                }else {
//                    //套餐时长中的天数
//                    Integer count = packageTime.getCountDays();
//                    //拿到用户自己的拥有时间
//                    Date expirationTime = packageRecord1.getExpirationTime();
                    //常用偏移：套餐到期时间
                    DateTime newDate2 = DateUtil.offsetDay(expirationTime, count);

                    this.packageRecordMapper.updates(id,newDate2);
                }
            }else {
                //常用偏移：套餐到期时间
                DateTime newDate2 = DateUtil.offsetDay(expirationTime, count);

                this.packageRecordMapper.updates(id,newDate2);
            }
        }

        @Override
        public BigDecimal xufeijiage(PackagecVo packagecVo) {
        if (ObjectUtil.isEmpty(packagecVo)){
            Result.error("套餐不能为空");
        }
            Long patid = packagecVo.getPatid();
            PackageTime packageTime = this.packageTimeMapper.selectById(patid);
            if (ObjectUtil.isEmpty(packageTime)){
                Result.error("套餐时长不能为空");
            }
            BigDecimal timePrice = packageTime.getPrice();
            //拿到用户自己的卡卷
            Long id = packagecVo.getId();
            CardDisplay cardDisplay = this.cardDisplayMapper.selectLists(id);
            System.err.println("cardDisplay------>"+cardDisplay);
            if (cardDisplay!=null){
                //拿到套餐卡卷的金额
                Integer type = cardDisplay.getType();
                if (type==0){
                    BigDecimal countPrice = cardDisplay.getCountPrice();
                    //获取到卡卷进行减价
                    BigDecimal allPrice = timePrice.subtract(countPrice);
                    System.out.println("卡卷进行减价：allPrice------>allPrice------>"+allPrice);
                    this.cardRollMapper.updatere(id);
                    return allPrice;
                }
            }

            return timePrice;
        }

    /**
     * 根据token拿取用户信息
     * 根据用户信息拿取用户钱包
     * 根据用户钱包拿取我的套餐信息
     * @param token
     * @return
     */
    @Override
    public Result<MyWalletVo> getMyWallet(String token) {
        String s = this.redisTemplate.opsForValue().get("user:login" + token);
        User user = JSON.parseObject(s, User.class);
        if (ObjectUtil.isEmpty(user)){
            return Result.error("用户不存在");
        }
        log.info("user======》{}",user);
        QueryWrapper<Wallet> walletQueryWrapper = new QueryWrapper<>();
        walletQueryWrapper.eq("uid",user.getId());
        Wallet wallet = this.walletMapper.selectOne(walletQueryWrapper);
        if (ObjectUtil.isEmpty(wallet)){
            return Result.error("用户钱包不存在");
        }
        QueryWrapper<PackageRecord> packageRecordQueryWrapper = new QueryWrapper<>();
        packageRecordQueryWrapper.eq("wid",wallet.getId());
        packageRecordQueryWrapper.eq("status",0);
        PackageRecord packageRecord = this.packageRecordMapper.selectOne(packageRecordQueryWrapper);
        if (ObjectUtil.isEmpty(packageRecord)){
            return Result.error("用户未购买套餐");
        }
        MyWalletVo myWalletVo=this.packageRecordMapper.findMyPackageByFourTable(packageRecord);
        if (ObjectUtil.isEmpty(myWalletVo)){
            return Result.error("查询异常");
        }
        return Result.success(myWalletVo);
    }

    @Override
    public boolean findWallets(String token) {
        String s = this.redisTemplate.opsForValue().get("user:login" + token);
        User user = JSON.parseObject(s, User.class);
        System.err.println("user======>{}"+user);
        Integer a=this.walletMapper.findWallets(user.getId());
        if(a==0){
            return false;
        }else if(a==1){
            PackageRecord packageRecord=this.packageRecordMapper.findPackage(user.getId());
            this.walletMapper.updates(user.getId());
            this.packageRecordMapper.updatePackage(packageRecord.getPtid());
        }
        return true;

    }

}
